package com.onetime.mall.trading.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onetime.mall.trading.dao.MessageDao;
import com.onetime.mall.trading.entity.IdleItemEntity;
import com.onetime.mall.trading.entity.MessageEntity;
import com.onetime.mall.trading.entity.UserEntity;
import com.onetime.mall.trading.service.IdleItemService;
import com.onetime.mall.trading.service.MessageService;
import com.onetime.mall.trading.service.UserService;
import com.onetime.mall.trading.utils.PageUtils;
import com.onetime.mall.trading.utils.Query;
import com.onetime.mall.trading.vo.MessageAndUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("messageService")
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {

    @Autowired
    UserService userService;

    @Autowired
    IdleItemService idleItemService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MessageEntity> page = this.page(
                new Query<MessageEntity>().getPage(params),
                new QueryWrapper<MessageEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * // TODO: 2022/3/29  删除一条留言，未做用户身份验证
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteMessage(Long id) {
        return baseMapper.deleteById(id) == 1;
    }


    /**
     * // TODO: 2022/3/29 检查逻辑问题
     * 查询一个闲置下的所有留言，未做分页
     * 同时查出发送者和接收者的信息
     *
     * @param idleId 商品ID
     * @return 消息列表
     */
    @Override
    public List<MessageAndUserVo> getAllIdleMessage(Long idleId) {
        /*查询该商品的所有消息*/
        QueryWrapper<MessageEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("idle_id", idleId);
        List<MessageEntity> messageEntityList = this.list(wrapper);

        /*有消息*/
        if (messageEntityList.size() > 0) {
            List<MessageAndUserVo> collect = messageEntityList.stream().map(msg -> {
                /*查询消息所属用户ID（发送者）*/
                Long userId = msg.getUserId();
                UserEntity user = userService.getById(userId);
                /*查询：接受者*/
                Long toUserId = msg.getToUser();
                UserEntity toUserEntity = userService.getById(toUserId);

                /*装配：基本消息*/
                MessageAndUserVo vo = new MessageAndUserVo();
                BeanUtils.copyProperties(msg, vo);

                /*装配：发送者*/
                vo.setFromUserEntity(user);
                /*装配：接受者*/
                vo.setToUserEntity(toUserEntity);


                MessageEntity toMessage = new MessageEntity();


                if (msg.getToMessage() != null) {
                    /*查询：接受消息*/
                    Long toMsgId = msg.getToMessage();
                    MessageEntity toMessageEntity = baseMapper.selectById(toMsgId);
                    /*装配：接收消息*/
                    BeanUtils.copyProperties(toMessageEntity, toMessage);
                    vo.setToMessages(toMessage);
                }
                return vo;

            }).collect(Collectors.toList());
            return collect;
        } else {
            return null;
        }
    }


    /**
     * // TODO: 2022/3/29  获取一个用户收到的所有留言，未做分页查询
     * 同时查询出用户的信息和闲置的信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<MessageAndUserVo> getAllMyMessage(Long userId) {
        /*查询回复该用户的所有信息*/
        QueryWrapper<MessageEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("to_user", userId);
        List<MessageEntity> list = baseMapper.selectList(wrapper);

        if (list.size() > 0) {
            List<MessageAndUserVo> collect = list.stream().map(msg -> {
                Long idleId = msg.getIdleId();
                IdleItemEntity idleItem = idleItemService.getById(idleId);
                Long msgUserId = msg.getUserId();
                UserEntity user = userService.getById(msgUserId);

                MessageAndUserVo vo = new MessageAndUserVo();
                BeanUtils.copyProperties(msg, vo);

                vo.setFromUserEntity(user);
                vo.setIdleItemle(idleItem);

                return vo;
            }).collect(Collectors.toList());

            return collect;
        } else {
            return null;
        }
    }


    /**
     * 获取一条留言
     *
     * @param id 消息id
     * @return
     */
    @Override
    public MessageEntity getMessage(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 增加一条留言
     *
     * @param messageEntity 留言消息
     * @return true or false
     */
    @Override
    public boolean addMessage(MessageEntity messageEntity) {
        return baseMapper.insert(messageEntity) == 1;
    }
}